package hidalgo.expenses.activity;

import hidalgo.expenses.R;
import hidalgo.expenses.SessionManager;
import hidalgo.expenses.adapter.AccountViewAdapter;
import hidalgo.expenses.dao.AccountDao;
import hidalgo.expenses.entities.Account;
import hidalgo.expenses.utils.HideAnimation;
import hidalgo.expenses.utils.Properties;
import hidalgo.expenses.widgets.ActionBar;

import java.util.ArrayList;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AccountsActivity extends BaseActivity {

	private ActionBar actionBar;

	private ListView accountListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.accounts_activity);

		accountListView = (ListView) findViewById(R.id.accountList);

		registerForContextMenu(accountListView);

		accountListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Toast.makeText(AccountsActivity.this, "accoundId :" + id,
						Toast.LENGTH_SHORT).show();

				Intent intent = new Intent(AccountsActivity.this,
						TransactionsActivity.class);
				intent.putExtra("ACCOUNTID", (int) id);
				startActivity(intent);

			}

		});
		
		setUpActionBar();

		populateAccounts();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		int id = (int) accountListView.getAdapter().getItemId(info.position);

		menu.setHeaderTitle("Desea...");
		menu.add(0, id, 0, "Editar");
		menu.add(0, id, 0, "Eliminar");

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Eliminar") {
			deleteNote(item.getItemId());
		} else if (item.getTitle() == "Editar") {
			editAccount(item.getItemId());
		} else {
			return false;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		unregisterForContextMenu(accountListView);
	}

	private void deleteNote(final int id) {
		new AsyncTask<Integer, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(Integer... params) {

				return AccountDao.deleteById((int) params[0]);
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(AccountsActivity.this,
							"Eliminado correctamente", Toast.LENGTH_SHORT)
							.show();
					
					((AccountViewAdapter)accountListView.getAdapter()).removeAccount(id);
					((AccountViewAdapter)accountListView.getAdapter()).notifyDataSetChanged();
					
				} else {
					Toast.makeText(AccountsActivity.this, "Error al eliminar",
							Toast.LENGTH_SHORT).show();
				}

			};

		}.execute(id);
	}

	private void setUpActionBar() {

		actionBar = (ActionBar) findViewById(R.id.actionBar);
		actionBar.setTitle("Cuentas");
		// set home icon that does nothing when the user clicks on it
		actionBar.setHomeLogo(R.drawable.ic_title_home_default,
				new OnClickListener() {
					public void onClick(View v) {
						AccountsActivity.this.finish();
					}
				});
		// sets an action icon that displays a Toast upon clicking
		actionBar.addActionIcon(R.drawable.ic_add,
				new OnClickListener() {
					public void onClick(View v) {

						// pop up to create new activity
						openAddAccountDialog(AccountsActivity.this);

						Toast.makeText(AccountsActivity.this, "Nueva nota",
								Toast.LENGTH_SHORT).show();
					}

				});
	}

	private void openAddAccountDialog(Context context) {
		// custom dialog
		final Dialog dialog = new Dialog(context);

		// prevent the default title-bar from being displayed
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_edit_account);

		final EditText etxtAccountName = (EditText) dialog
				.findViewById(R.id.etxtAccountName);
		TextView txtActionName = (TextView) dialog
				.findViewById(R.id.txtActionName);
		Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);

		txtActionName.setText("Nueva Cuenta");
		btnAccept.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// create new Account
				Account account = new Account(0, etxtAccountName.getText()
						.toString(), SessionManager.userId);

				addAccount(account);

				dialog.dismiss();
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void openEditAccountDialog(Context context, final Account account) {
		// custom dialog
		final Dialog dialog = new Dialog(context);

		// prevent the default title-bar from being displayed
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_edit_account);

		final EditText etxtAccountName = (EditText) dialog
				.findViewById(R.id.etxtAccountName);
		TextView txtActionName = (TextView) dialog
				.findViewById(R.id.txtActionName);
		Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);

		txtActionName.setText("Editar Cuenta");

		etxtAccountName.setText(account.getName());

		btnAccept.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// edit the Account

				account.setName(etxtAccountName.getText().toString());

				updateAccount(account);

				dialog.dismiss();
			}
		});

		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	private void editAccount(int accountId) {

		new AsyncTask<Integer, Integer, Account>() {

			protected void onPreExecute() {
				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);
			};

			@Override
			protected Account doInBackground(Integer... params) {

				int accountId = params[0];

				return AccountDao.getAccountById(accountId);
			};

			protected void onPostExecute(Account account) {

				if (account != null) {

					openEditAccountDialog(AccountsActivity.this, account);

				} else {

					Toast.makeText(AccountsActivity.this,
							"Error al cargar Cuenta", Toast.LENGTH_SHORT)
							.show();
				}

			};

		}.execute(accountId);

	}

	private void updateAccount(final Account account) {
		new AsyncTask<Account, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(Account... params) {

				return AccountDao.update((Account) params[0]);
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(AccountsActivity.this,
							"Cuenta editada correctamente", Toast.LENGTH_SHORT)
							.show();
					
					((AccountViewAdapter)accountListView.getAdapter()).updateAccount(account);
					((AccountViewAdapter)accountListView.getAdapter()).notifyDataSetChanged();
				} else {
					Toast.makeText(AccountsActivity.this,
							"Error al editar Cuenta", Toast.LENGTH_SHORT)
							.show();
				}

			};

		}.execute(account);
	}

	private void addAccount(final Account account) {
		new AsyncTask<Account, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(Account... params) {

				return AccountDao.insert((Account) params[0]);
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(AccountsActivity.this,
							"Cuenta creada correctamente", Toast.LENGTH_SHORT)
							.show();
					
					((AccountViewAdapter)accountListView.getAdapter()).addAccount(account);
					((AccountViewAdapter)accountListView.getAdapter()).notifyDataSetChanged();
					
				} else {
					Toast.makeText(AccountsActivity.this,
							"Error al crear nueva Cuenta", Toast.LENGTH_SHORT)
							.show();
				}

			};

		}.execute(account);
	}

	public void populateAccounts() {

		new AsyncTask<Integer, Integer, ArrayList<Account>>() {

			protected void onPreExecute() {
				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);
			};

			@Override
			protected ArrayList<Account> doInBackground(Integer... params) {

				int userId = params[0];

				return AccountDao.getAccountsByUser(userId);
			};

			protected void onPostExecute(
					java.util.ArrayList<Account> accountList) {

				if (accountList != null) {

					AccountViewAdapter accountAdapter = new AccountViewAdapter(
							AccountsActivity.this, R.layout.account_item,
							accountList);

					accountListView.setAdapter(accountAdapter);

				}

				actionBar.getProgressBar().completeLoading();
				actionBar.getProgressBar().startAnimation(
						new HideAnimation(1.0f, 1.0f, 1.0f, 0.0f, 500,
								actionBar.getProgressBar(), true));

			};

		}.execute(SessionManager.userId);
	}
}
